package reportd

import (
	"time"

	"github.com/globalsign/mgo"
	"github.com/globalsign/mgo/bson"

	"github.com/pkg/errors"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/core/common"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/core/repo/mgorepo/baser"
	creportd "gogs.xiaoyuanjijiehao.com/antlinker/antcms/core/reportd"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/log"

	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/ddd"
)

type reportRepo struct {
	baser.BaseRepo
}

// 新增信息
func (r *reportRepo) AddReport(ctx ddd.Context, report creportd.ReportDesc) (id string, err error) {
	ci := &collReport{}
	ci.FullDesc(report)
	ci.Status = 0
	ci.ReportID = r.NextID()
	ci.RepTime = time.Now()
	err = r.DBInsert(ctx, ci)
	if err != nil {
		return "", err
	}

	return ci.ReportID, nil
}

// 处理结果
func (r *reportRepo) DoResult(ctx ddd.Context, reportid string, result creportd.ReportResult) (err error) {
	update := bson.M{
		"result":   result.Result,
		"procUID":  result.ProcUID,
		"procTime": time.Now(),
		"status":   1,
	}
	ci := &collReport{ReportID: reportid}
	err = r.DBUpdateCollAggregate(ctx, ci, update)
	if err != nil {
		return errors.Wrapf(err, "处理举报(%v)结果失败。", reportid)
	}

	return nil
}

// 获取指定信息：根据唯一标识获取信息实体
func (r *reportRepo) GetReport(ctx ddd.Context, reportid string) (ra *creportd.ReportAggregate, err error) {
	a, err := r.GetByCollAggregate(ctx, &collReport{ReportID: reportid})
	if err != nil {
		if err == mgo.ErrNotFound {
			return nil, nil
		}
		return nil, err
	}
	ra = a.(*creportd.ReportAggregate)
	return
}
func (r *reportRepo) parseSearch(is creportd.ReportSearch) bson.M {
	query := bson.M{}

	if is.Key != "" {

		query["content"] = bson.M{"$regex": is.Key}
	}
	return query
}

// 分页获取信息列表：根据唯一标识获取下一页指定数量的信息实体集合
// total 总数量
func (r *reportRepo) QueryPage(ctx ddd.Context, is creportd.ReportSearch, pi common.PageInfo) (npi common.PageResult, result []creportd.ReportAggregate, err error) {
	query := r.parseSearch(is)

	var cs []collReport

	npi, err = r.DBQueryPage(ctx, collNameReport, pi, "_id", query, nil, nil, &cs)

	if err != nil {
		if err == mgo.ErrNotFound {
			err = nil
			npi.End = 1
			return
		}
		err = errors.Wrapf(err, "查询信息失败。查询条件:%v 。分页信息:%v", is, pi)
		return
	}
	if len(cs) == 0 {
		npi.End = 1
		return
	}
	result = make([]creportd.ReportAggregate, 0, len(cs))
	for _, c := range cs {
		ia := c.ToReportAggregate()
		// 初始化聚合
		ia.Init(ia, r.AggregateRoot(), c.ReportID)
		result = append(result, *ia)
	}

	return
}

// 删除信息 标记删除
func (r *reportRepo) Delete(ctx ddd.Context, reportid string) error {
	update := bson.M{
		"status": -1,
	}
	err := r.DBUpdateID(ctx, collNameReport, reportid, update)
	if err != nil {
		return err
	}
	err = r.DeleteCache(ctx, &collReport{ReportID: reportid})
	if err != nil {
		log.Warnf("删除信息%v缓存时失败：%v", reportid, err)
	}
	return nil
}
